package net;

import org.jboss.netty.buffer.ChannelBuffer;

import util.ChannelBufferUtil;

public class RPC implements IMessageHandler {
	public Dispatcher dispatcher;
	public IObjectReader objectReader;
	public IVersionChecker checker; 
	
	public RPC(Dispatcher dispatcher, IObjectReader reader, IVersionChecker checker) {
		this.dispatcher = dispatcher;
		this.objectReader = reader;
		this.checker = checker;
	}
	
	@Override
	public boolean handle(ClientContext ctx, ChannelBuffer data) throws Exception {
		String methodName = ChannelBufferUtil.readString(data);
		if (!checker.check(methodName, ctx.version)) {
			ctx.syner.prepareMsg("QueryResult");
			ctx.syner.sendMsg(true);
			return true;
		}
    	int size = data.readByte();
    	int type;
    	Object[] args = new Object[size+1];
    	args[0] = ctx;
    	for (int i = 1; i <= size; i++) {
    		type = data.readByte();
    		switch (type) {
    		case Protocol.TYPE_BYTE:
    			args[i] = data.readByte();
    			break;
    		case Protocol.TYPE_INT:
    			args[i] = data.readInt();
    			break;
    		case Protocol.TYPE_STRING:
    			args[i] = ChannelBufferUtil.readString(data);
    			break;
    		case Protocol.TYPE_OBJECT:
    			args[i] = objectReader.read(ctx.version, data);
//    			args[i] = ChannelBufferUtil.readObject(data);
    			break;
    		case Protocol.TYPE_INT_ARRAY:
    			args[i] = ChannelBufferUtil.readIntArray(data);
    			break;
    		case Protocol.TYPE_STRING_ARRAY:
    			args[i] = ChannelBufferUtil.readStringArray(data);
    			break;    			
    		}
    	}
    	return dispatcher.dispatch(methodName, args);
	}
}
